<template>
    <div class="form-wrapper">
        <el-card class="form">
            <h1 class="title">用户登录</h1>
            <el-form  ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="账户" prop="name" required>
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password" required>
                    <el-input type="password" v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">登录</el-button>
                    <el-button @click="goToRegister">注册</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import Service from '@/service/request'

export default {
    data() {
        return{
            form: {
                name: '',
                password: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur'}
                ]
            }
        }
    },
    methods: {
        // 用户注册
        goToRegister () {
            this.$router.push('/register')
        },
       // 用户登录 
       onSubmit() {
            this.$refs.form.validate(async (valid) => {
                if(valid) {
                    const data = await Service.login(this.form.name, this.form.password)
                    // console.log('>>>>>>', 'data', data);
                    if (data.code == 200) {
                        this.$store.commit('setUserId', data.obj.id)
                        this.$store.commit('setUserPermission', data.obj.role)
                        localStorage.setItem('permission', data.obj.role + '')
                        this.$message.info('登录成功')
                        this.$router.push('/home')  // 页面跳转到 首页
                    }
                    else {
                        this.$message.error('请输入正确的账号密码！')
                    }
                }
            })
        }
    }
}
</script>

<style>
.title {
    margin-bottom: 40px;
}
.form-wrapper {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
}

.form {
    width: 500px;
    height: 400px;
    position: absolute;
    top: 30%;
    left: calc(50% - 250px);

}

</style>